# Copyright (c) 2019-present Dirk Jahnke (dirk.jahnke@mailbox.org)
#
# 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 requests
from platformio import util
import shutil
import gzip

Import('env')

#print env
#print env.Dump()

project_config = util.load_project_config()
version = project_config.get("common", "app_version")

#
# Transfer and gzip files to proj/data directory
#

def transfer_file(source, target):
    """ copy and compress the file """

    try:
        with gzip.open(target + '.gz', 'wb') as target_fid:
            with open(source, 'rb') as source_fid:
                target_fid.writelines(source_fid)
        print('Compress {}'.format(source))
    except FileNotFoundError:
        os.makedirs(os.path.dirname(target))
        transfer_file(source, target)


def build_files(source, target, env):
    # copy & gzip files from src/data to data
    #firmware_path = str(source[0])
    #firmware_name = os.path.basename(firmware_path)
    source_path = os.path.join(env['PROJECTSRC_DIR'], "data")
    destination_path = env['PROJECTDATA_DIR']

    print("========= Preparing file system (SPIFF) files from " + source_path)
    print("=== Destination: " + destination_path)
    print("Cleanup destination path " + destination_path)
    shutil.rmtree(destination_path)
    os.mkdir(destination_path)

    for path, _, files in os.walk(source_path):
        for file in files:
            source = os.path.join(path, file)
            target = os.path.join(destination_path, file)
            print("Copy " + source + " to " + target)
            transfer_file(source, target)

def build_files_spiffs(source, target, env):
    print("Build files, reason: pre spiffs.bin build")
    build_files(source, target, env)

def build_files_buildprog(source, target, env):
    print("Build files, reason: buildprog target")
    build_files(source, target, env)

def build_files_buildfs(source, target, env):
    print("Build files, reason: buildfs target")
    build_files(source, target, env)

# Custom upload command and program name
env.AddPreAction("$BUILD_DIR/spiffs.bin", build_files_spiffs)
#env.AddPreAction("$BUILD_DIR/firmware.bin", build_files)
env.AddPreAction("buildprog", build_files_buildprog)
#env.AddPreAction("uploadfs", build_files_uploadfs)
#env.AlwaysBuild(env.Alias("buildfs", None, build_files_buildfs))
env.AddPreAction("buildfs", build_files_buildfs)
