# Copyright (c) 2013-2020, SIB - Swiss Institute of Bioinformatics and
#                          Biozentrum - University of Basel
# 
# 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.


'''
Create a very basic raw model from alignments and template structures.
Conserved parts are copied from the template and an incomplete pdb file is
generated.

Example usage:
  pm build-rawmodel -f aln.fasta -p tpl.pdb
    This reads a target-template alignment from aln.fasta and a matching
    structure from tpl.pdb and produces a raw model which is stored as
    model.pdb.

Please see the ProMod3 documentation for details on more advanced usage.
'''

import os
import ost
from ost import io
from promod3 import modelling
from promod3.core import pm3argparse, helper

# make sure we see output when passing '-h'
ost.PushVerbosityLevel(2)

# parse command line
parser = pm3argparse.PM3ArgumentParser(__doc__, action=True)
parser.AddAlignment()
parser.AddStructure(attach_views=True)
parser.AssembleParser()
parser.add_argument('-o', '--model-file', metavar='<FILENAME>', type=str,
                    default='model.pdb', help='File to store model coordinates'+
                                              ' (default: %(default)s).')
# lots of checking being done here -> see PM3ArgumentParser
opts = parser.Parse()

# get raw model
try:
    mhandle = modelling.BuildRawModel(opts.alignments)
except Exception as ex:
    helper.MsgErrorAndExit("Failed to generate raw model! An exception of "+
                           "type " + type(ex).__name__ + " occured: " + str(ex),
                           3)

# output
ost.PopVerbosityLevel()
try:
    io.SavePDB(mhandle.model, opts.model_file)
    if not os.path.isfile(opts.model_file):
        raise IOError("Failed to write model file.")
except Exception as ex:
    helper.MsgErrorAndExit("Failed to write model file '%s'." % opts.model_file, 4)
