import stdnum.exceptions
import logging
from sql import Column, Literal
from sql.aggregate import Min
from sql.functions import CharLength
from stdnum import get_cc_module
import urllib.request
from bs4 import BeautifulSoup
from decimal import Decimal
from trytond.i18n import gettext
from trytond.model import (
    DeactivableMixin, Index, ModelSQL, ModelView, MultiValueMixin, Unique,
    ValueMixin, convert_from, fields, sequence_ordered)
from trytond.model.exceptions import AccessError
from trytond.pool import Pool
from trytond.pyson import Bool, Eval
from trytond.tools import is_full_text, lstrip_wildcard
from trytond.transaction import Transaction, inactive_records
from trytond.wizard import Button, StateTransition, StateView, Wizard

logger = logging.getLogger(__name__)

class VesselType(ModelSQL, ModelView):
    "Vessel Type"
    __name__ = 'stock.vessel.type'

    name = fields.Char('Vessel Type', required=True)
    cargo_mode = fields.Selection([
        ('bulk', 'Bulk'),
        ('tanker', 'Tanker'),
        ('container', 'Container'),
    ], 'Cargo Mode', required=True)

    dwt_min = fields.Integer('Min DWT')
    dwt_max = fields.Integer('Max DWT')

    teu_min = fields.Integer('Min TEU')
    teu_max = fields.Integer('Max TEU')

class Vessel(
        DeactivableMixin, ModelSQL, ModelView,
        MultiValueMixin):
    "Vessel"
    __name__ = 'trade.vessel'
    _rec_name = 'vessel_name'

    vessel_name = fields.Char('Name',required=True)
    vessel_imo = fields.Char("IMO")
    vessel_type = fields.Many2One('stock.vessel.type',"Vessel Type")
    vessel_year = fields.Char("Built year")
    vessel_premium = fields.Numeric("Premium(%)",readonly=False)
    vessel_info = fields.Function(fields.Text("Position"),'get_info')
    image = fields.Binary("Vessel position",readonly=True)
    
    @classmethod
    def default_vessel_imo(cls):
        return '9900459'
    
    def get_info(self,name=None):        
        hdr = {
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding': 'none',
            'Accept-Language': 'en-US,en;q=0.8',
            'Connection': 'keep-alive'}
        if not self.vessel_imo:
            return
        url = r'https://www.vesselfinder.com/en/vessels/VOS-TRAVELLER-IMO-' + self.vessel_imo
        req = urllib.request.Request(url, None, hdr)
        try:
            with urllib.request.urlopen(req) as response:
                the_page = response.read()
        except urllib.error.HTTPError:
            return ""
        parsed_html = BeautifulSoup(the_page)
        tables = parsed_html.findAll("section")
        row = tables[0].findAll('div')
        aux = row[0].findAll('p')
        inf = ''
        for a in aux:
            inf += str(a)
        inf = inf.replace("<strong>","")
        inf = inf.replace("</strong>","")
        inf = inf.replace("</p>]","")
        inf = inf.replace("</p>","")
        inf = inf[18:]
        inf = inf.replace("\n", "")
        inf = inf.replace("\\n", "")
        inf = inf.replace("\r", "")
        inf = inf.replace("\\r", "")
        inf = inf.replace("\n\r", "")
        inf = inf.replace("\\n\\r", "")
        inf = inf.replace("    ", " ")
        inf = inf.replace("   ", " ")
        inf = inf.replace("  ", " ")
        inf = inf.replace(". ", ".\n")
        #aux = aux.replace(".", ".\\r")
        #logger.info("GET_INFO:%s",aux)
        return inf

    @classmethod
    def getVesselByName(cls, vessel, imo=None):
        vessel = vessel.upper()
        v = cls.search([('vessel_name', '=', vessel)], limit=1)
        if v:
            return v[0]
        else:
            v = cls()
            v.vessel_name = vessel
            v.vessel_imo = imo
            cls.save([v])
            return v
    
    @classmethod
    def remover(cls,tr = ""):
        char_to_keep = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")
        for item in tr:
            if item not in char_to_keep:
                tr = tr.replace(item, "")
        return tr

    # @fields.depends('vessel_year')
    # def on_change_with_vessel_premium(self, name=None):
    #     if self.vessel_year:
    #         config = Pool().get('trade.configuration')(1)
    #         Date = Pool().get('ir.date')
    #         diff = Date.today().year - int(self.vessel_year)
    #         logger.info("YEARDIFF:%s",diff)
    #         if diff >= 26 and diff <= 30:
    #             return config.old_vessel_rate_26_30
    #         elif diff >= 31 and diff <= 35:
    #             return config.old_vessel_rate_31_35
    #         else:
    #             return Decimal(0)
    