# Copyright 2017-present Adtran, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import structlog
import xmltodict
from twisted.internet import reactor
from twisted.internet.defer import returnValue, inlineCallbacks
from voltha.protos.device_pb2 import ImageDownload
from voltha.protos.common_pb2 import AdminState

log = structlog.get_logger()

# TODO: Following two would be good provisionable parameters
DEFAULT_AUTO_AGE_MINUTES = 10
DEFAULT_MAX_JOB_RUN_SECONDS = 3600 * 4     # Some OLT files are 250MB+


class Download(object):
    """Class to wrap an image download"""

    def __init__(self, handler, request, protocols):
        self._handler = handler
        self._deferred = None
        self.device_id = request.id
        self._name = request.name
        self._url = request.url
        self._crc = request.crc
        self._version = request.image_version
        self._local = request.local_dir
        self._save_config = request.save_config
        self._supported_protocols = protocols

        self._download_state = ImageDownload.DOWNLOAD_UNKNOWN
        self._failure_reason = ImageDownload.UNKNOWN_ERROR
        self._image_state = ImageDownload.IMAGE_UNKNOWN
        self._additional_info = ''
        self._downloaded_octets = 0

        # Server profile info
        self._server_profile_name = None
        self._scheme = None
        self._host = ''
        self._port = None
        self._path = ''
        self._auth = None

        # Download j
ob info
        self._download_job_name = None

        self._age_out_period = DEFAULT_AUTO_AGE_MINUTES
        self._max_execution = DEFAULT_MAX_JOB_RUN_SECONDS

    def __str__(self):
        return "ImageDownload: {}".format(self.name)

    @staticmet
hod
    def create(handler, request, supported_protocols):
        """
        Create and start a new image download

        :param handler: (AdtranDeviceHandler) Device download is for
        :param request: (ImageDownload) Request
        :param supported_protocols: (list) download methods allowed (http, tftp, ...)
        """
        download = Download(handler, request, supported_protocols)
        download._deferred = reactor.callLater(0, download.start_download)

        return download

    @property
    def name(self):
        return self._name

    @property
    def download_state(self):
        return self._download_state

    @property
    def failure_reason(self):
        return self._failure_reason

    @property
    def image_state(self):
        return self._image_state

    @property
    def additional_info(self):
        return self._additional_info

    @property
    def downloaded_bytes(self):
        return self._downloaded_octets

    @property
    def profile_name(self):
        return self._server_profile_name

    def _cancel_deferred(self):
        d, self._deferred = self._deferred, None
        try:
            if d is not None and not d.called:
                d.cancel()
        except Exception as e:
            pass

    @inlineCallbacks
    def start_download(self):
        import uuid
        log.info('download-start', name=self.name)
        if not self.parse_url():
            self._download_failed()
            returnValue('failed url parsing')

        self._download_state = ImageDownload.DOWNLOAD_STARTED
        self._failure_reason = ImageDownload.NO_ERROR

        ##############################################################
        # Configure the file server profile
        try:
            self._additional_info = 'Configuring Download Server profile'
            self._server_profile_name = 'VOLTHA.download.{}'.format(uuid.uuid4())
            profile = self.server_profile_xml
            yield self._handler.netconf_client.edit_config(profile)

        except Exception as e:
            log.exception('server-profile', e=e)
            self._server_profile_name = None
            self._failure_reason = ImageDownload.UNKNOWN_ERROR
            self._additional_info += ': Failure: {}'.format(e.message)
            self._download_failed()
            raise

        ##############################################################
        # Configure the software download maintenance job
        try:
            self._additional_info = 'Configuring Image Download Job'
            self._download_job_name = 'VOLTHA.download.{}'.format(uuid.uuid4())
            job = self.download_job_xml
            yield self._handler.netconf_client.edit_config(job)

        except Exception as e:
            log.exception('server-profile', e=e)
            self._download_job_name = None
            self._failure_reason = ImageDownload.UNKNOWN_ERROR
            self._additional_info += ': Failure: {}'.format(e.message)
            self._download_failed()
            raise

        ##############################################################
        # Schedule a task to monitor the download
        try:
            self._additional_info = 'Monitoring download status'
            self._deferred = reactor.callLater(0.5, self.monitor_download_status)

        except Exception as e:
            log.exception('server-profile', e=e)
            self._failure_reason = ImageDownload.UNKNOWN_ERROR
            self._additional_info += ': Failure: {}'.format(e.message)
            self._download_failed()
            raise

        returnValue('started')

    def parse_url(self):
        from urllib3 import util, exceptions
        try:
            results = util.parse_url(self._url)

            # Server info
            self._scheme = results.scheme.lower()
            if self._scheme not in self._supported_protocols:
                self._failure_reason = ImageDownload.INVALID_URL
                self._additional_info = "Unsupported file transfer protocol: {}".format(results.scheme)
                return False

            self._host = results.host
            self._port = results.port
            self._path = results.path
            self._auth = results.auth
            return True

        except exceptions.LocationValueError as e:
            self._failure_reason = ImageDownload.INVALID_URL
            self._additional_info = e.message
            return False

        except Exception as e:
            self._failure_reason = ImageDownload.UNKNOWN_ERROR
            self._additional_info = e.message
            return False

    @property
    def server_profile_xml(self):
        assert self._scheme in ['http', 'https', 'ftp', 'sftp', 'tftp'], 'Invalid protocol'

        xml = """
              <file-servers xmlns="http://www.adtran.com/ns/yang/adtran-file-servers">
                <profiles>
                  <profile>"""

        xml += '<name>{}</name>'.format(self._server_profile_name)
        xml += '<connection-profile>'
        xml += '  <host>{}</host>'.format(self._host)
        xml += '  <port>{}</port>'.format(self._port) if self._port is not None else '<use-standard-port/>'

        if self._scheme in ['http', 'https']:
            xml += '  <protocol '
            xml += 'xmlns:adtn-file-srv-https="http://www.adtran.com/ns/yang/adtran-file-servers-https">' +\
                   'adtn-file-srv-https:{}'.format(self._scheme)
            xml += '  </protocol>'

        elif self._scheme == 'sftp':
            xml += '  <protocol '
            xml += 'xmlns:adtn-file-srv-sftp="http://www.adtran.com/ns/yang/adtran-file-servers-sftp">' +\
                   'adtn-file-srv-sftp:sftp'
            xml += '  </protocol>'

        elif self._scheme in ['ftp', 'tftp']:
            xml += '<protocol>adtn-file-srv:{}</protocol>'.format(self._scheme)

        if self._auth is not None:
            user_pass = self._au