#!/usr/bin/env python

import os

def main():
    dirname = os.path.dirname(os.path.realpath(__file__))
    src_path = os.path.join(dirname, '..', 'reactopya', 'templates', '__project_name___dev', 'src', 'components', 'ReactopyaModel.js')
    dst_path1 = os.path.join(dirname, '..', 'reactopya_jup', 'lib', 'ReactopyaModel.js')
    dst_path2 = os.path.join(dirname, '..', 'reactopya', 'templates', '__project_name__', '__project_name__', 'electron', 'src', 'ReactopyaModel.js')
    dst_path3 = os.path.join(dirname, '..', 'reactopya', 'templates', '__project_name___bundle', 'ReactopyaModel.js')

    _copy_if_needed(src_path, dst_path1)
    _copy_if_needed(src_path, dst_path2)
    _copy_if_needed(src_path, dst_path3)

def _copy_if_needed(src_path, dst_path):
    st_mode = os.stat(src_path).st_mode
    src_code = _read_text_file(src_path)
    src_code = '////////////////////////\n// DO NOT EDIT THIS FILE\n////////////////////////\n\n\n\n\n\n' + src_code
    _write_text_file_if_changed(dst_path, src_code, st_mode)        

def _read_text_file(fname):
    try:
        with open(fname, 'r') as f:
            return f.read()
    except:
        return ''

def _write_text_file_if_changed(fname, txt, st_mode):
    if os.path.exists(fname):
        txt_existing = _read_text_file(fname)
        st_mode_existing = os.stat(fname).st_mode
    else:
        txt_existing = None
        st_mode_existing = None
    if (txt != txt_existing) or ((st_mode is not None) and (st_mode != st_mode_existing)):
        print('Writing: {}'.format(fname))
        with open(fname, 'w') as f:
            f.write(txt)
        os.chmod(fname, st_mode)
        return True
    else:
        # print('Unmodified: {}'.format(fname))
        return False

if __name__ == "__main__":
    main()