# -*- coding: utf-8 -*-
'''
    Spider campaigns system logic.
'''

# This file is part of spider.

# Distributed under the terms of the last AGPL License.
# The full license is in the file LICENCE, distributed as part of this software.

__author__ = 'Team Machine'


import arrow
import motor
import uuid

import logging

from tornado import gen

from spider.messages import campaigns
#from spider.messages import inbound

from spider.tools import clean_structure, clean_results


class Campaigns(object):
    '''
        Spider campaigns
    '''

    @gen.coroutine
    def get_campaign_list(self, account, status, page_num):
        '''
            Get campaign list
        '''
        page_num = int(page_num)
        page_size = self.settings.get('page_size')
        campaign_list = []

        find_query = {'account':account}

        logging.info(status)

        if status != 'all':
            find_query['status'] = status

        query = self.db.campaigns.find(find_query, {'_id':0})
        q = query.sort([('_id', -1)]).skip(int(page_num) * page_size).limit(page_size)

        try:
            while (yield query.fetch_next):
                campaign = q.next_object()
                campaign_list.append(campaign)
        except Exception, e:
            logging.exception(e)
            raise gen.Return(e)

        finally:
            raise gen.Return(campaign_list)

    @gen.coroutine
    def get_campaign(self, account, campaign_uuid):
        '''
            Get campaign
        '''
        message = None
        try:
            result = yield self.db.campaigns.find_one(
                {
                'account':account,
                'uuid':campaign_uuid},
                {'_id':0}
            )
            if result:
                campaign = campaigns.Campaign(result)
                campaign.validate()
                message = clean_structure(campaign)
        except Exception, e:
            logging.exception(e)
            raise e
        finally:
            raise gen.Return(message)
    
    @gen.coroutine
    def new_campaign(self, struct):
        '''
            New campaign
        '''
        try:
            campaign = campaigns.Campaign(struct)
            campaign.validate()
            campaign = clean_structure(campaign)
        except Exception, e:
            logging.error(e)
            raise e

        try:
            result = yield self.db.campaigns.insert(campaign)
            message = campaign.get('uuid')
        except Exception, e:
            logging.error(e)
            message = str(e)

        raise gen.Return(message)

    @gen.coroutine
    def modify_campaign(self, account, campaign_uuid, struct):
        '''
            Modify campaign
        '''
        try:
            campaign = campaigns.ModifyCampaign(struct)
            campaign.validate()
            campaign = clean_structure(campaign)
        except Exception, e:
            logging.error(e)
            raise e


        logging.error(campaign)

        try:
            result = yield self.db.campaigns.update(
                {'account':account,
                 'uuid':campaign_uuid},
                {'$set':campaign}
            )
            logging.info(result)            
        except Exception, e:
            logging.error(e)
            message = str(e)

        raise gen.Return(bool(result.get('n')))

    @gen.coroutine
    def replace_campaign(self, account, campaign_uuid, struct):
        '''
            Replace campaign
        '''
        try:
            campaign = campaigns.Campaign(struct)
            campaign.validate()
            campaign = clean_structure(campaign)
        except Exception, e:
            logging.error(e)
            raise e

        try:
            result = yield self.db.campaigns.update(
                {'account':account,
                 'uuid':campaign_uuid},
                {'$set':campaign}
            )
            logging.info(result)            
        except Exception, e:
            logging.error(e)
            message = str(e)

        raise gen.Return(bool(result.get('n')))

    @gen.coroutine
    def remove_campaign(self, account, campaign_uuid):
        '''
            Remove campaign
        '''
        message = None
        try:
            message = yield self.db.campaigns.remove(
                {'account':account, 'uuid':campaign_uuid}
            )
        except Exception, e:
            logging.error(e)
            message = str(e)

        raise gen.Return(bool(message.get('n')))


    # check_exist needs some testing. 

    @gen.coroutine
    def check_exist(self, campaign_uuid):
        '''
            Check if a given campaign exist
        '''
        try:
            exist = yield self.db.campaigns.find_one(
                                {'uuid': campaign_uuid},
                                {'uuid':1,
                                 'name':1,
                                 '_id':0})
            exist = (True if exist else False)

        except Exception, e:
            logging.error(e)
            message = str(e)

        raise gen.Return(exist)