#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# System modules
from datetime import datetime
from urllib.parse import urlencode

# Third-party modules
import requests

# Other templates
from ..utils import check
from ..utils.logger import log
from .basedevice import BaseDevice


class DlinkDCSCamera(BaseDevice):
    '''Base wrapper class for Dlink DCS 5020l cameras.'''

    def __init__(self, url):
        '''Constructor.'''

        self.url = url
        self.addr = self.url
        self.timeout = 3
        self.error = []

    @check.request_errors
    def get(self, method, params=[], text=True):
        '''Send a HTTP GET request to the device address.'''

        res = requests.get(f"{self.addr}/{method}.cgi",
                           params=params,
                           timeout=self.timeout)

        if text:
            res_list = res.text.split("\r\n")[:-1]
            try:
                return dict([r.split("=", 1) for r in res_list])
            except ValueError as e:
                log.error(e)
                self.error.append(e)
                return res
        else:
            try:
                return res.content
            except AttributeError as e:
                log.error(e)
                self.error.append(e)
                return None

    @check.request_errors
    def put(self, method, params={}):
        '''Send a HTTP GET request to the device address.'''

        res = requests.get(f"{self.addr}/{method}.cgi",
                           params=params,
                           timeout=self.timeout)
        value = res

        return value

    # def time_to_string(self, time):
    #     '''Convert a datetime into the HH:MM:SS string format.'''
    #     return datetime.strftime(time, '%H:%M:%S')


class Webcam(DlinkDCSCamera):
    '''Implementation of the Telescope commands mocking my Alpaca
       Telescope wrapper.'''

    @property
    def description(self):
        '''Get IP Camera Information.'''
        res = self.get('common/info')
        return res

    @property
    def stream_info(self):
        '''Get the IP Camera Video stream info.'''
        return self.get('config/stream_info')

    @property
    def altaz(self):
        '''Get the IP Camera Network Pan Tilt Zoom.'''
        res = self.get('config/ptz_move')
        if not res:
            return res
        self._altaz = list(map(int, [res["t"], res["p"]]))
        return self._altaz

    @altaz.setter
    def altaz(self, a):
        params = {"p": int(a[1]), "t": int(a[0])}
        res = self.put("config/ptz_move", params=params)
        self._altaz = self.altaz

    @property
    def is_moving(self):
        '''Get the IP Camera Motion Detection settings.'''
        return self.get('config/motion')

    @property
    def clock(self):
        '''Get IP Camera Data Time settings.'''
        return self.get('config/datetime')

    @property
    def image(self):
        '''Get IP Camera image in raw format.'''
        res = self.get('image/jpeg', text=False)

        return res

    @property
    def video(self):
        '''Get IP Camera video as mjpeg stream.'''
        res = self.get('video/mjpg', text=False)

        return res

    @property
    def save_image(self, filename="temp.jpeg"):
        '''Save a IP Camera image snapshot.'''
        res = self.image
        if not res:
            return res
        with open(filename, 'wb') as f:
            f.write(res)

        return filename

    @property
    def network(self):
        '''Get the IP Camera Network settings.'''
        return self.get('config/network')

    @property
    def wireless(self):
        '''Get the IP Camera Wireless information.'''
        return self.get('config/wireless')

    @property
    def ptzpresets(self):
        '''Get the IP Camera Network Pan Tilt Zoom Preset List'''
        return self.get('config/ptz_preset_list')

    # stream = requests.get(url, stream=True)
    # if stream.ok:
    #     chunk_size = 1024
    #     for chunk in stream.iter_content(chunk_size=chunk_size):
    #         interpret_video_and_write_to_socket_somehow(chunk, blocking=True)

    # NOT OK

    @property
    def version(self):
        '''Get IP Camera CGI version.'''
        return self.get('cgiversion')

    @property
    def inetwork(self):
        '''Get the IP Camera Network information.'''
        return self.get('inetwork')

    @property
    def isystem(self):
        '''Get the IP Camera System information.'''
        return self.get('isystem')

    @property
    def user(self):
        '''Get the IP Camera user setttings.'''
        return self.get('user')

    @property
    def user_list(self):
        '''Get the list of IP Camera users.'''
        return self.get('userlist')

    @property
    def upload(self):
        '''Get the IP Camera FTP Upload settings.'''
        return self.get('upload')

    @property
    def daynight(self):
        '''Get the IP Camera Day Night Mode settings.'''
        return self.get('daynight')

    @property
    def email(self):
        '''Get the IP Camera Email notification settings.'''
        return self.get('email')

    @property
    def sound_detection(self):
        '''Get the IP Camera Sound Detection settings.'''
        return self.get('sdbdetection')
