# -*- coding: utf-8 -*-
##############################################################################
#
#    Odoo, Open Source Management Solution
#    Copyright (C) 2016-TODAY Prime Consulting SA, Cape Verde (<http://prime.cv>).
#
##############################################################################

from odoo import models, fields, api
from datetime import datetime
from dateutil.relativedelta import relativedelta

import logging
_logger = logging.getLogger(__name__)

class SaleSubscription(models.Model):
    _inherit = "sale.subscription"

    @api.model
    def action_cron_send_expiry_notification(self):
        today = datetime.now().date()
        expiring_in_3days = today + relativedelta(days = 3)
        month_expiry_date = today + relativedelta(days = 30)
        
        subscriptions = self.search(['|', ('date', '=', month_expiry_date), ('date', '=', expiring_in_3days)])
        for subscription in subscriptions:
            _logger.info('Sending Email notification to alert Subscription Expiry. Subscription: %s'%(subscription.display_name))
            subscription.send_email_notification('mail_template_subscription_expiration')

    @api.multi
    def send_email_notification(self, email_template=False):
        if email_template:
            ir_model_data = self.env['ir.model.data']
            try:
                template_id = ir_model_data.get_object_reference('sale_contract_notification', email_template)[1]
            except ValueError:
                template_id = False

            if template_id:
                mail_template = self.env['mail.template']
                template_ids = mail_template.browse(template_id)
                template_ids.send_mail(self.id, force_send=True) 
            else:
                _logger.error('Email template not found. Template: %s Subscription Id: %s'%(email_template, self.id))
        return True
