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

"""Websocket part"""

# System modules
import os
import time
from datetime import datetime
import requests

# Third-party modules
from astropy.io import fits

class Status:
    def __init__(self):
        self.last = {}

    def initial(self, socketio, urls):
        for url in urls:
            name = url.split("?")[0] # maybe different?
            name = name.split("5533")[1] # maybe different?
            socketio.emit(name, self.last[name])

status = Status()

def send_timestamp(socketio):
    while True:
        unix = datetime.utcnow().timestamp()
        socketio.emit('timestamp', unix)
        socketio.sleep(1)


def send_status(socketio, url, sleep=2, once=False):
    name = url.split("?")[0] # maybe different?
    name = name.split("5533")[1] # maybe different?

    # First time
    socketio.sleep(sleep)
    old = requests.get(url).json()
    status.last[name] = old

    while not once:
        socketio.sleep(sleep)
        res = requests.get(url).json()
        #print(res)
        status.last[name] = res
        if res != old:
            socketio.emit(name, res)
            old = res


def send_webcam(socketio, url, sleep=1):

    name = url.split("?")[0] # maybe different?
    name = name.split("5533")[1] # maybe different?
    #print(name, url)

    while True:
        socketio.sleep(sleep)
        res = requests.get(url).json()
        img = res["response"].encode("ISO-8859-1")
        status.last[name] = bytes(img)
        socketio.emit(name, bytes(img))


def tail_f(socketio, num_lines=30, sleep=0.25, once=False):
    today = datetime.utcnow().isoformat().split("T")[0]
    filename = f"./data/log/OARPAF.{today}.log"
    file_size = os.path.getsize(filename)

    # First time
    with open(filename, 'r') as f:
        lines = f.readlines()[-num_lines:]
        socketio.emit('new_lines', lines)  # Initial lines on first page load
        status.last['new_lines'] = lines

    while not once:
        socketio.sleep(sleep)  # Sleep before checking again
        current_size = os.path.getsize(filename)
        if current_size < file_size:
            file_size = 0
        elif current_size > file_size:
            # File has been appended
            with open(filename, 'r') as f:
                f.seek(file_size)
                new_lines = f.readlines()
                file_size = current_size
                if new_lines:
                    socketio.emit('new_lines', new_lines)
                    status.last['new_lines'] = new_lines



def send_binary(socketio):
    # Third-party modules
    import numpy as np

    # while True:
    for i in range(1):
        dtype = "uint16"
        shape = (248,248)
        matrix = np.random.uniform(0, 65535, shape).astype(dtype)
        binary_data = matrix.tobytes()
        unix = datetime.utcnow().timestamp()
        data_bundle = {
            "shape": matrix.shape,
            "dtype": dtype,
            "data": binary_data,
            "timestamp": unix,
        }

        socketio.emit('data_bundle', data_bundle)
        print((datetime.utcnow().timestamp()-unix), "emitted")
        print(f"bin {len(binary_data)}")

        socketio.sleep(1)


def send_fits(socketio):
    """download a fits"""

    with fits.open("./temp.fits") as hdul:
        matrix = hdul[0].data
        header = hdul[0].header
        unix = datetime.utcnow().timestamp()
        data_bundle = {
            "shape": matrix.shape,
            "dtype": matrix.dtype.name,
            "data": matrix.tobytes(),
            "header": [list(c) for c in header.cards],
            "timestamp": unix,
        }
        socketio.emit('data_fits', data_bundle)
        print((datetime.utcnow().timestamp()-unix), "emitted")
        print(f"bin {len(matrix)}")
