# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import time
import datetime
from dateutil.relativedelta import relativedelta
import math

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _
from odoo.tools.misc import formatLang
import json

import urlparse
import uuid

from datetime import date

class EtourismBookingCancel(models.TransientModel):
    _name = 'etourism.booking.cancel.wizard'
    _description = 'Open Booking Cancel Wizard'

    @api.model
    def default_get(self, fields):
        context = self.env.context
        res = super(EtourismBookingCancel, self).default_get(fields)
        booking_group = self.env['etourism.booking.group'].browse(context.get('active_ids'))
        lines = []
        temp = [lines.append(line.id) for line in booking_group.booking_line if line.state in ('confirmed','pending')]

        res.update(booking_ids=[[6,0, lines]])
        return res

    booking_group_id = fields.Many2one('etourism.booking.group', string='Booking Group')
    booking_ids = fields.Many2many('etourism.booking', 'booking_group_bookings_cancel')
    num_bookings = fields.Integer(string='Num Bookings')
    cancellation_reason_id = fields.Many2one('etourism.booking.cancellation.reason', 'Reason for cancellation', required=True)

    @api.multi
    def action_cancel(self):
        print "LET'S CANCEL::::::::::::"
        for booking in self:
            booking_group_id=booking.booking_group_id
            booking_lines = self.env['etourism.booking']
            cancelIds =[]
            if booking.booking_ids:
                for bk in booking.booking_ids:
                    print "BOOKING::::::::::::: ",bk.id
                    cancelIds.append(bk.id)
                    bk.write({'state': 'cancelled'})
            bk_not_selected = booking_lines.sudo().search([('id', 'not in', cancelIds), ('state', '!=', 'cancelled'), ('booking_group_id', '=', booking_group_id.id)])
            for a in booking_group_id.booking_line:
                print "STATES:::::::::::::", a.state
            print "NOT SELECTED:::::::::::", len(bk_not_selected)
            if len(bk_not_selected) == 0:
                print "WILL NOTIFY:::::::::::::"
                booking_group_id.write({'state': 'cancelled'})
                booking_group_id.sudo().send_email_notification('mail_template_etourism_booking_cancellation')
            raise ValidationError(_('Test'))
            #booking_group_id.write({'state': 'cancelled'})
