import os
import uuid
from datetime import datetime
from django.conf import settings
from django.http import HttpResponse
from rest_framework import status
from rest_framework.response import Response
import owncloud
from owncloud import (HTTPResponseError)

import xml.etree.ElementTree as ET
import requests


class Owncloud:
    @staticmethod
    def upload_damage_photo(filename, depot_id):
        _, ext = os.path.splitext(filename)
        oc = owncloud.Client(settings.OWNCLOUD_URL)
        oc.login(settings.OWNCLOUD_USER, settings.OWNCLOUD_PASSWORD)
        path = f"{settings.OWNCLOUD_DAMAGES_FOLDER}{str(depot_id)}"
        try:
            oc.file_info(path)
        except HTTPResponseError:
            _ = oc.mkdir(path)
        owncloud_filename = f"{datetime.today().strftime('%Y%m%d')}_{uuid.uuid4()}{ext}"
        owncloud_fullpath = path + "/" + owncloud_filename
        oc.put_file(owncloud_fullpath, filename)
        file_info = oc.share_file_with_link(owncloud_fullpath)
        return file_info.get_link()

    @staticmethod
    def get_damages(depot_id):
        oc = owncloud.Client(settings.OWNCLOUD_URL)
        oc.login(settings.OWNCLOUD_USER, settings.OWNCLOUD_PASSWORD)
        files = oc.list(f"{settings.OWNCLOUD_DAMAGES_FOLDER}{str(depot_id)}")
        damages = []
        for file_info in files:
            if file_info.is_dir():
                continue
            link_info = oc.share_file_with_link(file_info.path)
            damages.append(link_info.get_link())
        return Response(damages, status=status.HTTP_200_OK)


    @staticmethod
    def get_damages_webdav(depot_id):
        oc = owncloud.Client(settings.OWNCLOUD_URL)
        oc.login(settings.OWNCLOUD_USER, settings.OWNCLOUD_PASSWORD)
        path = f"{settings.OWNCLOUD_DAMAGES_FOLDER}{str(depot_id)}"
        files = oc.list(path)
        damages = []

        for file_info in files:
            if file_info.is_dir():
                continue

            original_filename = os.path.basename(file_info.path)
            link_info = oc.share_file_with_link(file_info.path)
            share_url = link_info.get_link()
            token = share_url.rstrip('/').split('/')[-1]

            damages.append({
                "token": token,
                "filename": original_filename
            })

        return Response(damages, status=status.HTTP_200_OK)


def proxy_owncloud_image(request, token, filename):
    url = f"{settings.OWNCLOUD_URL}/public.php/webdav/{filename}"
    r = requests.get(url, auth=(token, ''), stream=True)
    if r.status_code == 200:
        content_type = r.headers.get('Content-Type', 'image/jpeg')
        return HttpResponse(r.content, content_type=content_type)
    return HttpResponse("Not found", status=404)