# Copyright (C) 2022 RozK
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from pathlib import Path

from engine import load_shader

#TODO: preprocessing (at least includes)

def load(vert_name, frag_name = ''):
    path = Path('.') / 'game' / 'shaders'
    if not frag_name:
        frag_name = vert_name
    def _cleanup(_line):
        return _line.partition('//')[0].strip()
    def _filter(_line):
        return _line
    def _convert(_line):
        return bytes(_line, 'utf-8') + b'\n'
    def load_source(_path):
        if not _path.exists():
            print("Cannot find", _path)
            return None
        return list(map(_convert, filter(_filter, map(_cleanup, open(_path, 'rt')))))
    print("Loading vertex shader", vert_name)
    vert_lines = load_source(path / (vert_name + '_opengles.vert'))
    if not vert_lines:
        print("Error: Vertex shader is empty.")
        return None
    print("Loading fragment shader", frag_name)
    frag_lines = load_source(path / (frag_name + '_opengles.frag'))
    if not frag_lines:
        print("Error: Fragment shader is empty.")
        return None
    return load_shader(vert_lines, frag_lines)
