import os
import zipfile
import datetime
import io
import re
from lxml import etree

counter = 0
src_dir = r"U:\PRJ\2015\T3\Примеры_для_адаптаций\БКА"


def date_formatter(date_string):
    """
    Выясняет формат записи даты и времени, возвращает дату в фомате datetime
    :param date_string: дата и время в форме строки
    :return: datetime object
    """
    if re.match(r'\d{4}-\d{2}-\d{2}.\d{2}:\d{2}:\d{2}$', date_string) is not None:  # BKA, ZY-3 вариант 1
        try:
            return datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S')
    elif re.match(r'\d{14}\.\d+', date_string) is not None:  # ZY-3 вариант 2
        return datetime.datetime.strptime(date_string, '%Y%m%d%H%M%S.%f')
    elif re.match(r'\d{4}.\d{2}.\d{2}.\d{2}:\d{2}:\d{2}\.\d+.?$', date_string) is not None:  # DG, TH-1 и т.д.
        try:
            return datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
        except ValueError:
            return datetime.datetime.strptime(date_string, '%Y %m %d %H:%M:%S.%f')


def im_scrape(target_file_path):
    global counter
    if re.match(r'\d{6}\.XML', os.path.basename(target_file_path), re.IGNORECASE) is not None:  # BKA
        counter += 1
        print("Сканирую", target_file_path)
        xml = etree.parse(target_file_path)
        root = xml.getroot()
        # ================================================
        if root[3][0].get("VALUE") == 'true':
            sat_name = 'BKA'
        else:
            sat_name = 'KANOPUS'
        vendor_id = root.get("ID")
        part = 0
        acq_datetime = date_formatter(root[2][2].get("VALUE"))
        cloud_pct = root[4][5].get("VALUE")
        off_nadir = root[4][2].get("VALUE")
        # TODO найти и доработать для другие варианты синтеза
        if root[8][0].get("VALUE") == 'true':
            spec_mode = 'PSS'
        else:
            spec_mode = 'MSS'
        gsd = root[6][1].get("VALUE")
        sun_elev = root[5][1].get("VALUE")
        sun_azim = root[5][0].get("VALUE")
        # (root[4][0].get("VALUE"))
        for level in (root[4][0].getchildren()):
            if level.get('KEY') == root[4][0].get("VALUE"):
                vend_level = level.get('TEXT')
                break
        # TODO найти и доработать для другие варианты продуктов
        if vend_level == 'C':
            inn_level = 'C'
        else:
            inn_level = 'X'
        url = None



        print(
            sat_name, vendor_id, acq_datetime, cloud_pct, off_nadir, spec_mode, gsd, sun_elev, sun_azim, vend_level,
            inn_level, url,)

        # print(sat_name, vendor_id, part, acq_datetime, cloud_pct, off_nadir, spec_mode, gsd, sun_elev, sun_azim,
        #       vend_level, inn_level, url, geom, comment=None)


for dirpath, dirnames, filenames in os.walk(src_dir):
    for filename in filenames:
        file_path = os.path.join(dirpath, filename)
        im_scrape(file_path)
