/*
  This file is part of ccbuild.

  ccbuild is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  ccbuild 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 General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with ccbuild.  If not, see <http://www.gnu.org/licenses/>.
*/






#include "system.ih"

void System::dotgraphFor(Source *target, ostream &str) {

    //Collect all Source pointers needed
    inspect(target);

    //Header
    str << "//\n"
        << "//DOT graph generated by ccbuild version "<< Options::version << "\n"
        << "//For more information visit: " << Options::homepage << "\n"
        << "//\n\n";


    str << "digraph \"" << target->outputFilename() << "\" {\n"
        << "\trankdir=\"LR\";\n\toverlap=false;\n\tsplines=true\n";
    str << "\tnode [shape=box, margin=\"0.15,0.055\"];\n";


    vector<Source *> srcList;


    //Graph target dependencies or all targets dependencies
    if(Options::verbose) {
        srcList.push_back(target);
        collectTargets(srcList, false); //Read all sources and binary targets
    } else {
        target->dependencies(srcList);

        //Also graph the target itself
        srcList.push_back(target);
    }

    //Set colours
    __foreach(src, srcList)
    if((*src)->isBinTarget()) {
        str << "\t\"" << (*src)->filename() << "\" [color=lightblue, style=filled];\n";
    } else if((*src)->isObjectTarget()) {
        str << "\t\"" << (*src)->filename() << "\" [color=lightgrey, style=filled];\n";
    }


    //Connect all found dependecies and their direct deps
    __foreach(src, srcList) {
        vector<Source *> locals;
        (*src)->directDeps(locals);

        //Connectie tussen directDeps en target
        __foreach(l, locals) {
            (*l)->genDeps();
            str << "\t\"" << (*src)->filename() << "\" -> \""
                <<  (*l)->filename()<< "\";\n";
        }

        if(Options::verbose) {
            //Show ignores
            vector<string> ignores;
            (*src)->ignoredDeps(ignores);
            if(!ignores.empty()) {
                str << "\t\"" << (*src)->filename() << "\" -> \"";
                copy(ignores.begin(), ignores.end(), ostream_iterator<string>(str, "\\n"));
                str << "\" [color=red, style=dashed, arrowhead=inv];\n";
            }
        }
    }

    str << "}\n";
}
