import requests
import logging
from django.db import connections
from django.contrib import messages
import datetime
import os

SETTING = os.environ['WORKOUTTEST_SETTING']
if SETTING == "PROD":
    from aitrainer_backoffice.aitrainer_backoffice.models.customer import Customer
else:    
    from aitrainer_backoffice.models.customer import Customer


class Mautic:
    
    def syncNoDataOldDownloaders(self):
        qs = Customer.objects.raw('SELECT * FROM customer c left join exercises e on c.customer_id = e.customer_id WHERE trial_date_sync <= NOW() - INTERVAL 2 DAY AND e.exercise_id is null AND c.last_exercise_sync is null')
        logger = logging.getLogger(__name__)
        logger.info("Syncronising lang...")

        headers = {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        }
        index = 0
        for customer in qs:
            data = "mauticform[email]=" + customer.email + \
                   "&mauticform[database_id]=" + str(customer.customer_id) + \
                   "&mauticform[lastexercise]=1900-01-01" + \
                   "&mauticform[formId]=7" + \
                   "&mauticform[formName]=appdatasync"

            print(data)

            form_url = 'https://mautic.workouttest.org/form/submit?formId=7'
            response = requests.post(form_url, data=data.encode('utf-8'), headers=headers)
            print(customer.email + " " +str(response.status_code))

            if response.status_code == 200:
                with connections["live"].cursor() as cursor:
                    cursor.execute("UPDATE customer SET last_exercise_sync = NOW() WHERE customer_id="
                                   + str(customer.customer_id))
                    print(f'customer {customer.customer_id} is updated')

            index = index + 1

        print( "Syncronised customer count: " + str(index))        
        return True
    
    
    def syncNoDataNewSubscribes(self):
        qs = Customer.objects.raw('SELECT * FROM customer c left join exercises e on c.customer_id = e.customer_id WHERE c.date_add <= NOW() - INTERVAL 2 DAY AND e.exercise_id is null AND c.last_exercise_sync is null')
        logger = logging.getLogger(__name__)
        logger.info("Syncronising lang...")

        headers = {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        }
        index = 0
        for customer in qs:
            data = "mauticform[email]=" + customer.email + \
                   "&mauticform[database_id]=" + str(customer.customer_id) + \
                   "&mauticform[lastexercise]=1900-01-01" + \
                   "&mauticform[formId]=7" + \
                   "&mauticform[formName]=appdatasync"

            print(data)

            form_url = 'https://mautic.workouttest.org/form/submit?formId=7'
            response = requests.post(form_url, data=data.encode('utf-8'), headers=headers)
            print(customer.email + " " +str(response.status_code))

            if response.status_code == 200:
                with connections["live"].cursor() as cursor:
                    cursor.execute("UPDATE customer SET last_exercise_sync = NOW() WHERE customer_id="
                                   + str(customer.customer_id))
                    print(f'customer {customer.customer_id} is updated')

            index = index + 1

        print( "Syncronised customer count: " + str(index))        
        return True

    def syncLang(self):
        qs = Customer.objects.raw('SELECT * from customer WHERE lang is not null and lang_sync is null')
        logger = logging.getLogger(__name__)
        logger.info("Syncronising lang...")

        headers = {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        }
        index = 0
        for customer in qs:
            data = "mauticform[email]=" + customer.email + \
                   "&mauticform[database_id]=" + str(customer.customer_id) + \
                   "&mauticform[lang]=" + str(customer.lang) + \
                   "&mauticform[formId]=7" + \
                   "&mauticform[formName]=appdatasync"

            print(data)

            form_url = 'https://mautic.workouttest.org/form/submit?formId=7'
            response = requests.post(form_url, data=data.encode('utf-8'), headers=headers)
            print(customer.email + " " +str(response.status_code))

            if response.status_code == 200:
                with connections["live"].cursor() as cursor:
                    cursor.execute("UPDATE customer SET lang_sync = NOW() WHERE customer_id="
                                   + str(customer.customer_id))
                    print(f'customer {customer.customer_id} is updated')

            index = index + 1

        print( "Syncronised customer count: " + str(index))        
        return True
    
    def syncTrial(self):
        qs = Customer.objects.raw('select *  FROM customer WHERE trial_date <= NOW() - INTERVAL 10 DAY and trial_date_sync is null')
        logger = logging.getLogger(__name__)
        logger.info("Syncronising trial date...")

        headers = {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        }
        index = 0
        for customer in qs:
            data = "mauticform[email]=" + customer.email + \
                   "&mauticform[database_id]=" + str(customer.customer_id) + \
                   "&mauticform[trialdate]=1900-01-01" + \
                   "&mauticform[formId]=7" + \
                   "&mauticform[formName]=appdatasync"

            print(data)

            form_url = 'https://mautic.workouttest.org/form/submit?formId=7'
            response = requests.post(form_url, data=data.encode('utf-8'), headers=headers)
            print(customer.email + " " +str(response.status_code))

            if response.status_code == 200:
                with connections["live"].cursor() as cursor:
                    cursor.execute("UPDATE customer SET trial_date_sync = NOW() WHERE customer_id="
                                   + str(customer.customer_id))
                    print(f'customer {customer.customer_id} is updated')

            index = index + 1

        print( "Syncronised customer count: " + str(index))        
        return True


    def sync(self):
        logger = logging.getLogger(__name__)
        logger.info("Syncronising...")

        last_synced_date = self.get_last_synced_date()

        if len(last_synced_date) != 0:
            qs = Customer.objects.raw(
                'SELECT * from customer WHERE date_add > "' + last_synced_date + '" or synced_date is null')
        else:
            qs = Customer.objects.raw(
                'SELECT * from customer WHERE synced_date is null')

        headers = {
            'content-type': "application/x-www-form-urlencoded",
            'cache-control': "no-cache"
        }
        index = 0
        for customer in qs:
            goal = customer.goal if customer.goal is not None else ""
            fitness_level = customer.fitness_level if customer.fitness_level is not None else ""
            data = "mauticform[email]=" + customer.email + \
                   "&mauticform[f_name]=" + customer.name + \
                   "&mauticform[firstname]=" + customer.firstname + \
                   "&mauticform[goal]=" + goal + \
                   "&mauticform[fitness_level]=" + fitness_level + \
                   "&mauticform[subscribed]=" + str(customer.date_add) + \
                   "&mauticform[database_id]=" + str(customer.customer_id) + \
                   "&mauticform[formId]=1" + \
                   "&mauticform[formName]=appsync"

            print(data)

            form_url = 'https://mautic.workouttest.org/form/submit?formId=1'
            response = requests.post(form_url, data=data.encode('utf-8'), headers=headers)
            print(str(response.status_code))

            if response.status_code == 200:
                with connections["live"].cursor() as cursor:
                    cursor.execute("UPDATE customer SET synced_date = NOW() WHERE customer_id="
                                   + str(customer.customer_id))
            #if index == 0:
            #    break
            index = index + 1

        logger.info("Syncronised customer count: " + str(index))

        return True

    def get_last_synced_date(self):
        qs = Customer.objects.raw('SELECT customer_id, max(synced_date) as synced_date from customer')
        for c in qs:
            if c.synced_date is None:
                return ""
            synced_date = c.synced_date.strftime('%Y-%m-%d')
            print(synced_date)
            return synced_date

    def sync_frequent_users(self):
        print("SYNC FREQ USERS")
        return True