#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
import httpx
import logging
import datetime
import json
import unicodedata
from xlrd import open_workbook
from os.path import basename

# Configure logging
logging.basicConfig(
    filename='/var/log/importContacts.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s'
)

class Contact:
    def __init__(self, contact_type, default_language, company_name, last_name, first_name,
                 phone, fax, mobile, email, web_site, address_line1, address_line2, city_name,
                 post_code, region_code, state_name, country_code, country_id, to_the_attention_of,
                 currency_id, payment_terms, credit_limit, client_discount_rate):
        self.contact_type = contact_type
        self.default_language = default_language
        self.company_name = company_name
        self.last_name = last_name
        self.first_name = first_name
        self.phone = phone
        self.fax = fax
        self.mobile = mobile
        self.email = email
        self.web_site = web_site
        self.address_line1 = address_line1
        self.address_line2 = address_line2
        self.city_name = city_name
        self.post_code = post_code
        self.region_code = region_code
        self.state_name = state_name
        self.country_code = country_code
        self.country_id = country_id
        self.to_the_attention_of = to_the_attention_of
        self.currency_id = currency_id
        self.payment_terms = payment_terms
        self.credit_limit = credit_limit
        self.client_discount_rate = client_discount_rate

    def __str__(self):
        return (
            f"Contact object:\n"
            f"  contactType = {self.contact_type}\n"
            f"  defaultLanguage = {self.default_language}\n"
            f"  companyName = {self.company_name}\n"
            f"  lastName = {self.last_name}\n"
            f"  firstName = {self.first_name}\n"
            f"  Phone = {self.phone}\n"
            f"  Fax = {self.fax}\n"
            f"  Mobile = {self.mobile}\n"
            f"  Email = {self.email}\n"
            f"  webSite = {self.web_site}\n"
            f"  addressLine1 = {self.address_line1}\n"
            f"  addressLine2 = {self.address_line2}\n"
            f"  cityName = {self.city_name}\n"
            f"  postCode = {self.post_code}\n"
            f"  regionCode = {self.region_code}\n"
            f"  stateName = {self.state_name}\n"
            f"  countryCode = {self.country_code}\n"
            f"  countryId = {self.country_id}\n"
            f"  toTheAttentionOf = {self.to_the_attention_of}\n"
            f"  currencyId = {self.currency_id}\n"
            f"  paymentTerms = {self.payment_terms}\n"
            f"  creditLimit = {self.credit_limit}\n"
            f"  clientDiscountRate = {self.client_discount_rate}\n"
        )

def read_contacts_from_excel(filename):
    wb = open_workbook(filename)
    contacts = []
    for sheet in wb.sheets():
        nrows = sheet.nrows
        ncols = sheet.ncols
        # Skip header row (assumed to be the first row)
        for row in range(1, nrows):
            values = []
            for col in range(ncols):
                cell_value = sheet.cell(row, col).value
                try:
                    # Try converting numeric values to int and then to string
                    cell_value = str(int(cell_value))
                except (ValueError, TypeError):
                    cell_value = str(cell_value)
                values.append(cell_value)
            try:
                contact = Contact(*values)
                contacts.append(contact)
            except Exception as e:
                logging.warning(f"Error creating Contact from row {row}: {e}")
    return contacts

def create_contact_payload(item, organization_id):
    """Create a JSON payload for a contact based on its type."""
    if item.contact_type.upper() == 'ORGANIZATION':
        payload = {
            "contactId": -1,
            "organizationId": organization_id,
            "warnings": {},
            "contactType": item.contact_type,
            "defaultLanguage": item.default_language,
            "name": item.company_name,
            "type": "ContactDetailsOrganization",
            "webSite": item.web_site,
            "mobile": item.mobile,
            "phone": item.phone,
            "archived": False,
            "fax": item.fax,
            "email": item.email,
            "isCustomer": True,
            "isVendor": False,
            "addresses": [{
                "regionCode": item.region_code,
                "id": None,
                "name": "Main",
                "line1": item.address_line1,
                "line2": item.address_line2,
                "postCode": item.post_code,
                "city": item.city_name,
                "countryCode2": item.country_code,
                "countryId": item.country_id,
                "toTheAttentionOf": item.to_the_attention_of,
                "position": 0
            }],
            "banks": [],
            "supplier": {
                "paymentTerms": None
            },
            "client": {
                "orderAddressId": None,
                "invoiceAddressId": None,
                "paymentTerms": None,
                "lateNoticeMargin": None,
                "creditLimit": None,
                "clientDiscountRate": None,
                "orderAddressName": "Main",
                "invoiceAddressName": "Main"
            },
            "communications": []
        }
    else:
        payload = {
            "contactId": -1,
            "organizationId": organization_id,
            "warnings": {},
            "contactType": item.contact_type,
            "defaultLanguage": item.default_language,
            "firstName": item.first_name,
            "lastName": item.last_name,
            "middleName": None,
            "nationalityCountryId": None,
            "gender": None,
            "birthday": None,
            "permissionsTree": [],
            "isImpersonateOthers": False,
            "isActive": True,
            "staff": {
                "contactId": -1,
                "id": None,
                "avsNumber": None,
                "payrollCurrencyId": None,
                "employmentStartDate": None,
                "employmentEndDate": None,
                "employeeDocumentType": None,
                "documentNumber": None,
                "documentExpiryDate": None,
                "contractType": None,
                "maritalType": None,
                "maritalDate": None,
                "isSpouseWorking": None,
                "familyMembers": [],
                "timesheetPricingLines": [],
                "staffPayslips": [],
                "workPermit": None,
                "permitExpiryDate": None
            },
            "type": "ContactDetailsPerson",
            "webSite": item.web_site,
            "mobile": item.mobile,
            "phone": item.phone,
            "archived": False,
            "fax": item.fax,
            "email": item.email,
            "isCustomer": True,
            "isVendor": False,
            "addresses": [{
                "regionCode": item.region_code,
                "id": None,
                "name": "Main",
                "line1": item.address_line1,
                "line2": item.address_line2,
                "postCode": item.post_code,
                "city": item.city_name,
                "countryCode2": item.country_code,
                "countryId": item.country_id,
                "toTheAttentionOf": item.to_the_attention_of,
                "position": 0
            }],
            "banks": [],
            "supplier": {
                "paymentTerms": None
            },
            "client": {
                "orderAddressId": None,
                "invoiceAddressId": None,
                "paymentTerms": None,
                "lateNoticeMargin": None,
                "creditLimit": None,
                "clientDiscountRate": None,
                "orderAddressName": "Main",
                "invoiceAddressName": "Main"
            },
            "communications": []
        }
    return payload

def send_contacts(payload, webservice, headers):
    try:
        response = httpx.post(webservice, data=json.dumps(payload), headers=headers, timeout=10)
        response_data = response.json()
        if response_data['items'][0]['errorCode']['errorCode'] == 'NO_ERROR':
            new_contact_id = response_data['items'][0]['freshRow']['id']
            logging.debug(f"New contact inserted with ID {new_contact_id}")
            return new_contact_id
        else:
            logging.warning("Could not insert new contact!")
            return None
    except Exception as e:
        logging.exception(f"Exception occurred while sending contacts: {e}")
        raise

def main():
    # Read contacts from Excel file
    contacts = read_contacts_from_excel('Addresses_Test.xlsx')
    
    organization_id = '999999999999999'
    url = 'https://demo.wyzio.com'
    token = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
    
    headers = {
        'User-Agent': 'Wyzio/1.0',
        'weal-token': token,
        'cache-control': 'no-cache',
        'target-organization-id': organization_id,
        'Content-Type': 'application/json'
    }
    webservice = url + '/api-v1/contact/batch'
    
    for item in contacts:
        payload = create_contact_payload(item, organization_id)
        send_contacts(payload, webservice, headers)

if __name__ == '__main__':
    main()