text:
use super::metadata::file_metadata;
use super::utils::DIB;

use llvm;
use llvm::debuginfo::{DIScope, DISubprogram};
use trans::common::CrateContext;
use middle::pat_util;
use util::nodemap::NodeMap;

use libc::c_uint;
use syntax::codemap::{Span, Pos};
use syntax::{ast, codemap, ast_util};

// This procedure builds the *scope map* for a given function, which maps any
// given ast::NodeId in the function's AST to the correct DIScope metadata instance.
//
// This builder procedure walks the AST in execution order and keeps track of
// what belongs to which scope, creating DIScope DIEs along the way, and
// introducing *artificial* lexical scope descriptors where necessary. These
// artificial scopes allow GDB to correctly handle name shadowing.
pub fn create_scope_map(cx: &CrateContext,
                        args: &[ast::Arg],
                        fn_entry_block: &ast::Block,
                        fn_metadata: DISubprogram,
                        fn_ast_id: ast::NodeId)
                        -> NodeMap<DIScope> {
    let mut scope_map = NodeMap();

    let def_map = &cx.tcx().def_map;

    let mut scope_stack = vec!(ScopeStackEntry { scope_metadata: fn_metadata, name: None });
    scope_map.insert(fn_ast_id, fn_metadata);

    // Push argument identifiers onto the stack so arguments integrate nicely
    // with variable shadowing.
    for arg in args {
        pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, _, path1| {
            scope_stack.push(ScopeStackEntry { scope_metadata: fn_metadata,
                                               name: Some(path1.node.name) });
            scope_map.insert(node_id, fn_metadata);
        })
    }

    // Clang creates a separate scope for function bodies, so let's do this too.
    with_new_scope(cx,
                   fn_entry_block.span,
                   &mut scope_stack,
                   &mut scope_map,
                   |cx, scope_stack, scope_map| {
        walk_block(cx, fn_entry_block, scope_stack, scope_map);
    });

    return scope_map;
}

// local helper functions for walking the AST.
fn with_new_scope<F>(cx: &CrateContext,
                     scope_span: Span,
                     scope_stack: &mut Vec<ScopeStackEntry> ,
                     scope_map: &mut NodeMap<DIScope>,
                     inner_walk: F) where
    F: FnOnce(&CrateContext, &mut Vec<ScopeStackEntry>, &mut NodeMap<DIScope>),
{
    // Create a new lexical scope and push it onto the stack
    let loc = cx.sess().codemap().lookup_char_pos(scope_span.lo);
    let file_metadata = file_metadata(cx, &loc.file.name);
    let parent_scope = scope_stack.last().unwrap().scope_metadata;

    let scope_metadata = unsafe {
        llvm::LLVMDIBuilderCreateLexicalBlock(
            DIB(cx),
            parent_scope,
            file_metadata,
            loc.line as c_uint,
            loc.col.to_usize() as c_uint)
    };

    scope_stack.push(ScopeStackEntry { scope_metadata: scope_metadata, name: None });

    inner_walk(cx, scope_stack, scope_map);

    // pop artificial scopes
    while scope_stack.last().unwrap().name.is_some() {
        scope_stack.pop();
    }

    if scope_stack.last().unwrap().scope_metadata != scope_metadata {
        cx.sess().span_bug(scope_span, "debuginfo: Inconsistency in scope management.");
    }

    scope_stack.pop();
}

struct ScopeStackEntry {
    scope_metadata: DIScope,
    name: Option<ast::Name>
}

fn walk_block(cx: &CrateContext,
              block: &ast::Block,
              scope_stack: &mut Vec<ScopeStackEntry> ,
              scope_map: &mut NodeMap<DIScope>) {
    scope_map.insert(block.id, scope_stack.last().unwrap().scope_metadata);

    // The interesting things here are statements and the concluding expression.
    for statement in &block.stmts {
        scope_map.insert(ast_util::stmt_id(&**statement),
                         scope_stack.last().unwrap().scope_metadata);

        match statement.node {
            ast::StmtDecl(ref decl, _) =>
                walk_decl(cx, &**decl, scope_stack, scope_map),
            ast::StmtExpr(ref exp, _) |
            ast::StmtSemi(ref exp, _) =>
                walk_expr(cx, &**exp, scope_stack, scope_map),
            ast::StmtMac(..) => () // Ignore macros (which should be expanded anyway).
        }
    }

    if let Some(ref exp) = block.expr {
        walk_expr(cx, &**exp, scope_stack, scope_map);
    }
}

fn walk_decl(cx: &CrateContext,
             decl: &ast::Decl,
             scope_stack: &mut Vec<ScopeStackEntry> ,
             scope_map: &mut NodeMap<DIScope>) {
    match *decl {
        codemap::Spanned { node: ast::DeclLocal(ref local), .. } => {
            scope_map.insert(local.id, scope_stack.last().unwrap().scope_metadata);

            walk_pattern(cx, &*local.pat, scope_stack, scope_map);

            if let Some(ref exp) = local.init {
                walk_expr(cx, &**exp, scope_stack, scope_map);
            }
        }
        _ => ()
    }
}

fn walk_pattern(cx: &CrateContext,
                pat: &ast::Pat,
                scope_stack: &mut Vec<ScopeStackEntry> ,
                scope_map: &mut NodeMap<DIScope>) {

    let def_map = &cx.tcx().def_map;

    // Unfortunately, we cannot just use pat_util::pat_bindings() or
    // ast_util::walk_pat() here because we have to visit *all* nodes in
    // order to put them into the scope map. The above functions don't do that.
    match pat.node {
        ast::PatIdent(_, ref path1, ref sub_pat_opt) => {

            // Check if this is a binding. If so we need to put it on the
            // scope stack and maybe introduce an artificial scope
            if pat_util::pat_is_binding(def_map, &*pat) {

                let name = path1.node.name;

                // LLVM does not properly generate 'DW_AT_start_scope' fields
                // for variable DIEs. For this reason we have to introduce
                // an artificial scope at bindings whenever a variable with
                // the same name is declared in *any* parent scope.
                //
                // Otherwise the following error occurs:
                //
                // let x = 10;
                //
                // do_something(); // 'gdb print x' correctly prints 10
                //
                // {
                //     do_something(); // 'gdb print x' prints 0, because it
                //                     // already reads the uninitialized 'x'
                //                     // from the next line...
                //     let x = 100;
                //     do_something(); // 'gdb print x' correctly prints 100
                // }

                // Is there already a binding with that name?
                // N.B.: this comparison must be UNhygienic... because
                // gdb knows nothing about the context, so any two
                // variables with the same name will cause the problem.
                let need_new_scope = scope_stack
                    .iter()
                    .any(|entry| entry.name == Some(name));

                if need_new_scope {
                    // Create a new lexical scope and push it onto the stack
                    let loc = cx.sess().codemap().lookup_char_pos(pat.span.lo);
                    let file_metadata = file_metadata(cx, &loc.file.name);
                    let parent_scope = scope_stack.last().unwrap().scope_metadata;

                    let scope_metadata = unsafe {
                        llvm::LLVMDIBuilderCreateLexicalBlock(
                            DIB(cx),
                            parent_scope,
                            file_metadata,
                            loc.line as c_uint,
                            loc.col.to_usize() as c_uint)
                    };

                    scope_stack.push(ScopeStackEntry {
                        scope_metadata: scope_metadata,
                        name: Some(name)
                    });

                } else {
                    // Push a new entry anyway so the name can be found
                    let prev_metadata = scope_stack.last().unwrap().scope_metadata;
                    scope_stack.push(ScopeStackEntry {
                        scope_metadata: prev_metadata,
                        name: Some(name)
                    });
                }
            }

            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);

            if let Some(ref sub_pat) = *sub_pat_opt {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }
        }

        ast::PatWild(_) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
        }

        ast::PatEnum(_, ref sub_pats_opt) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);

            if let Some(ref sub_pats) = *sub_pats_opt {
                for p in sub_pats {
                    walk_pattern(cx, &**p, scope_stack, scope_map);
                }
            }
        }

        ast::PatQPath(..) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
        }

        ast::PatStruct(_, ref field_pats, _) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);

            for &codemap::Spanned {
                node: ast::FieldPat { pat: ref sub_pat, .. },
                ..
            } in field_pats {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }
        }

        ast::PatTup(ref sub_pats) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);

            for sub_pat in sub_pats {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }
        }

        ast::PatBox(ref sub_pat) | ast::PatRegion(ref sub_pat, _) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
            walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
        }

        ast::PatLit(ref exp) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
            walk_expr(cx, &**exp, scope_stack, scope_map);
        }

        ast::PatRange(ref exp1, ref exp2) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
            walk_expr(cx, &**exp1, scope_stack, scope_map);
            walk_expr(cx, &**exp2, scope_stack, scope_map);
        }

        ast::PatVec(ref front_sub_pats, ref middle_sub_pats, ref back_sub_pats) => {
            scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);

            for sub_pat in front_sub_pats {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }

            if let Some(ref sub_pat) = *middle_sub_pats {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }

            for sub_pat in back_sub_pats {
                walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
            }
        }

        ast::PatMac(_) => {
            cx.sess().span_bug(pat.span, "debuginfo::create_scope_map() - \
                                          Found unexpanded macro.");
        }
    }
}

fn walk_expr(cx: &CrateContext,
             exp: &ast::Expr,
             scope_stack: &mut Vec<ScopeStackEntry> ,
             scope_map: &mut NodeMap<DIScope>) {

    scope_map.insert(exp.id, scope_stack.last().unwrap().scope_metadata);

    match exp.node {
        ast::ExprLit(_)   |
        ast::ExprBreak(_) |
        ast::ExprAgain(_) |
        ast::ExprPath(..) => {}

        ast::ExprCast(ref sub_exp, _)     |
        ast::ExprAddrOf(_, ref sub_exp)  |
        ast::ExprField(ref sub_exp, _) |
        ast::ExprTupField(ref sub_exp, _) |
        ast::ExprParen(ref sub_exp) =>
            walk_expr(cx, &**sub_exp, scope_stack, scope_map),

        ast::ExprBox(ref place, ref sub_expr) => {
            place.as_ref().map(
                |e| walk_expr(cx, &**e, scope_stack, scope_map));
            walk_expr(cx, &**sub_expr, scope_stack, scope_map);
        }

        ast::ExprRet(ref exp_opt) => match *exp_opt {
            Some(ref sub_exp) => walk_expr(cx, &**sub_exp, scope_stack, scope_map),
            None => ()
        },

        ast::ExprUnary(_, ref sub_exp) => {
            walk_expr(cx, &**sub_exp, scope_stack, scope_map);
        }

        ast::ExprAssignOp(_, ref lhs, ref rhs) |
        ast::ExprIndex(ref lhs, ref rhs) |
        ast::ExprBinary(_, ref lhs, ref rhs)    => {
            walk_expr(cx, &**lhs, scope_stack, scope_map);
            walk_expr(cx, &**rhs, scope_stack, scope_map);
        }

        ast::ExprRange(ref start, ref end) => {
            start.as_ref().map(|e| walk_expr(cx, &**e, scope_stack, scope_map));
            end.as_ref().map(|e| walk_expr(cx, &**e, scope_stack, scope_map));
        }

        ast::ExprVec(ref init_expressions) |
        ast::ExprTup(ref init_expressions) => {
            for ie in init_expressions {
                walk_expr(cx, &**ie, scope_stack, scope_map);
            }
        }

        ast::ExprAssign(ref sub_exp1, ref sub_exp2) |
        ast::ExprRepeat(ref sub_exp1, ref sub_exp2) => {
            walk_expr(cx, &**sub_exp1, scope_stack, scope_map);
            walk_expr(cx, &**sub_exp2, scope_stack, scope_map);
        }

        ast::ExprIf(ref cond_exp, ref then_block, ref opt_else_exp) => {
            walk_expr(cx, &**cond_exp, scope_stack, scope_map);

            with_new_scope(cx,
                           then_block.span,
                           scope_stack,
                           scope_map,
                           |cx, scope_stack, scope_map| {
                walk_block(cx, &**then_block, scope_stack, scope_map);
            });

            match *opt_else_exp {
                Some(ref else_exp) =>
                    walk_expr(cx, &**else_exp, scope_stack, scope_map),
                _ => ()
            }
        }

        ast::ExprIfLet(..) => {
            cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
                                          Found unexpanded if-let.");
        }

        ast::ExprWhile(ref cond_exp, ref loop_body, _) => {
            walk_expr(cx, &**cond_exp, scope_stack, scope_map);

            with_new_scope(cx,
                           loop_body.span,
                           scope_stack,
                           scope_map,
                           |cx, scope_stack, scope_map| {
                walk_block(cx, &**loop_body, scope_stack, scope_map);
            })
        }

        ast::ExprWhileLet(..) => {
            cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
                                          Found unexpanded while-let.");
        }

        ast::ExprForLoop(..) => {
            cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
                                          Found unexpanded for loop.");
        }

        ast::ExprMac(_) => {
            cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
                                          Found unexpanded macro.");
        }

        ast::ExprLoop(ref block, _) |
        ast::ExprBlock(ref block)   => {
            with_new_scope(cx,
                           block.span,
                           scope_stack,
                           scope_map,
                           |cx, scope_stack, scope_map| {
                walk_block(cx, &**block, scope_stack, scope_map);
            })
        }

        ast::ExprClosure(_, ref decl, ref block) => {
            with_new_scope(cx,
                           block.span,
                           scope_stack,
                           scope_map,
                           |cx, scope_stack, scope_map| {
                for &ast::Arg { pat: ref pattern, .. } in &decl.inputs {
                    walk_pattern(cx, &**pattern, scope_stack, scope_map);
                }

                walk_block(cx, &**block, scope_stack, scope_map);
            })
        }

        ast::ExprCall(ref fn_exp, ref args) => {
            walk_expr(cx, &**fn_exp, scope_stack, scope_map);

            for arg_exp in args {
                walk_expr(cx, &**arg_exp, scope_stack, scope_map);
            }
        }

        ast::ExprMethodCall(_, _, ref args) => {
            for arg_exp in args {
                walk_expr(cx, &**arg_exp, scope_stack, scope_map);
            }
        }

        ast::ExprMatch(ref discriminant_exp, ref arms, _) => {
            walk_expr(cx, &**discriminant_exp, scope_stack, scope_map);

            // For each arm we have to first walk the pattern as these might
            // introduce new artificial scopes. It should be sufficient to
            // walk only one pattern per arm, as they all must contain the
            // same binding names.

            for arm_ref in arms {
                let arm_span = arm_ref.pats[0].span;

                with_new_scope(cx,
                               arm_span,
                               scope_stack,
                               scope_map,
                               |cx, scope_stack, scope_map| {
                    for pat in &arm_ref.pats {
                        walk_pattern(cx, &**pat, scope_stack, scope_map);
                    }

                    if let Some(ref guard_exp) = arm_ref.guard {
                        walk_expr(cx, &**guard_exp, scope_stack, scope_map)
                    }

                    walk_expr(cx, &*arm_ref.body, scope_stack, scope_map);
                })
            }
        }

        ast::ExprStruct(_, ref fields, ref base_exp) => {
            for &ast::Field { expr: ref exp, .. } in fields {
                walk_expr(cx, &**exp, scope_stack, scope_map);
            }

            match *base_exp {
                Some(ref exp) => walk_expr(cx, &**exp, scope_stack, scope_map),
                None => ()
            }
        }

        ast::ExprInlineAsm(ast::InlineAsm { ref inputs,
                                            ref outputs,
                                            .. }) => {
            // inputs, outputs: Vec<(String, P<Expr>)>
            for &(_, ref exp) in inputs {
                walk_expr(cx, &**exp, scope_stack, scope_map);
            }

            for &(_, ref exp, _) in outputs {
                walk_expr(cx, &**exp, scope_stack, scope_map);
            }
        }
    }
}


text:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>leuke tweede test leukleukleukdabjdgwfdyuaebfdwefbsefhbrhfe
            </div>
    </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
<meta name="application-name" content="{{app_name}}" />
<meta name="msapplication-config" content="{% url "tile:browserconfig" %}" />


text:
Bloc Chat
========

Bloc chat is a chat application designed in AngularJS and stores database information in firebase. Bloc chat was created to deminstrate Sarah Binion's codeing abilities.

Live Preview
---------
* [Link](http://www.sarahbinion.com)

Credits
-------
Bloc Chat was written and designed by [Sarah Binion](http://www.sarahbinion.com) while she attened Bloc's [Frontend Web Development Course](https://www.bloc.io/frontend-development-bootcamp).

Directory Structure
---------

```
├── Gruntfile.js
├── LICENSE
├── Procfile
├── README.md
├── node_modules
├── app
│   ├── assets
│   │   └── images
│   │       └── bChat3.png
│   │       └── bloc-logo-white.png
│   │       └── light.jpg
│   │       └── user.png
│	│
│   ├── index.html
│	│
│   ├── scripts
│   │   └── angular-ui-router.js
│   │   └── angular.js
│   │   └── app.js
│   │   └── ui-bootstrap-tpls-0.14.3.js
│	│
│   ├── styles
│   │   └── angular.css
│   │   └── app.css
│   │   └── jasine-standalone-2.3.4.zip
│   │   └── main.css
│   │   └── normalize.css
│	│
│   └── templates
│       └── landing.html
│		└── myModalContent.html
│
├── package.json
└── server.js
└── test.js
```

Installation
---------

The project uses Grunt to run tasks in development. Thoroughly review our [resource on using Grunt](https://www.bloc.io/resources/using-grunt) before using this application. It may also help to review [our resource on NPM and `package.json` files](https://www.bloc.io/resources/npm-and-package-json).

Install the project dependencies by running:

```
$ npm install
```

Run the Application
---------

Run the application using the Gruntfile's `default` task:

```
$ grunt
```

The default task runs a simple server on port 3000. To view it in a any browser, go to [http://localhost:3000](http://localhost:3000).

>Note that unless the application is run [via Live Preview in Brackets](#use-in-brackets-live-preview), the browser will need to be refreshed to view the most recent changes.

![Screenshot of project settings URL in Brackets](https://bloc-global-assets.s3.amazonaws.com/images-frontend/screenshots/bloc-frontend-project-starter/live_preview_project_settings.png)

The text in the application will not update on every keystroke, but changes will automatically push when you save the file.

Grunt plugins
---------

A list of the Grunt plugins in this application.

#### Watch

[Grunt watch](https://github.com/gruntjs/grunt-contrib-watch) watches for changes to file content and then executes Grunt tasks when a change is detected.

#### Copy

[Grunt copy](https://github.com/gruntjs/grunt-contrib-copy) copies files from our development folders and puts them in the folder that will be served with the frontend of your application.

#### Clean

[Grunt clean](https://github.com/gruntjs/grunt-contrib-clean) "cleans" or removes all files in your distribution folder (`dist`) so that logic in your stylesheets, templates, or scripts isn't accidentally overridden by previous code in the directory.

#### Hapi

[Grunt Hapi](https://github.com/athieriot/grunt-hapi) runs a server using [`HapiJS`](http://hapijs.com/). Happy is a Node web application framework with robust configuration options.


text:
var value = 0;

describe('Suite One', function () {
    test('Test One', function (done) {
        value++;
        done();
    });
});

module.exports = {
    getValue: function () { return value; }
}


text:
import os
from itertools import imap

import process
import benchmark
import globals
from text import format_columns

from error import ErrorType

def benchmark_iter():
    """Iterate over the benchmarks in 'bmks'."""
    # bmks is a dictionary from str to Future(Benchmark)
    return imap(lambda x: x.get(), globals.benchmarks.itervalues())

def list_benchmarks():
    """List all benchmarks on standard output."""
    print "Benchmarks:"
    for bmk in benchmark_iter(): print "  " + bmk.name

def describe_benchmarks():
    """Print descriptions of all benchmarks to standard output."""
    for bmk in benchmark_iter(): describe_benchmark(bmk)

def describe_benchmark(bmk):
    """Print a description of one benchmark to standard output."""

    print "  " + bmk.name
    print format_columns(bmk.describe(), 4)

def lookup_benchmark(name):
    """Find a benchmark, given its name.  Returns None if no benchmark
    is found with the given name or if the benchmark is invalid.
    If the benchmark cannot be found, an error is printed."""
    b = globals.benchmarks.get(name)
    if b is not None:
        bmk = b.get()
        if bmk.invalid is None:
            return bmk
        else:
            print "Error in benchmark:"
            print str(bmk.invalid)
            return None
    else:
        print "Cannot find benchmark"
        return None

def with_benchmark_named(name, action):
    """Look up the benchmark named 'name'.  If found, apply the action
    to it.  Otherwise, print an error message and return None."""

    bmk = lookup_benchmark(name)
    if bmk is not None:
      return action(bmk)

def compile_benchmark(bmk, version_name, platform=None):
    """Compile the benchmark 'bmk'."""
    try: impl = bmk.impls[version_name]
    except KeyError:
        print "Cannot find benchmark version"
        return

    return impl.build(bmk, platform)

def clean_benchmark(bmk, version_name=None, platform=None):
    """Remove the compiled code for one implementation of 'bmk'.  If
    no version is given, clean all versions."""

    if version_name:
        try: impl = bmk.impls[version_name]
        except KeyError:
            print "Cannot find benchmark version"
            return

        impl.clean(bmk, platform)
    else:
        # Clean all versions
        for impl in bmk.impls.itervalues():
            impl.clean(bmk, platform)

def run_benchmark(bmk, version_name, input_name, check=True, extra_opts=[], platform=None):
    """Run the benchmark 'bmk'."""
    try: impl = bmk.impls[version_name]
    except KeyError:
        print "Cannot find benchmark version"
        return ErrorType.CannotFindVersion

    try: data = bmk.datas[input_name]
    except KeyError:
        print "Cannot find data set"
        return ErrorType.CannotFindDataSet

    # Run the benchmark
    ret = impl.run(bmk, data, check, extra_opts=extra_opts, platform=platform)

    if ret is not ErrorType.Success:
        print "Run failed!"
        return ret

    # Verify the output
    if check:
        #zhangfeng zf
        print "Verify the output"
        success = impl.check(bmk, data)

        if not success:
            print "Output checking tool detected a mismatch"
            return ErrorType.OutputMismatch
    else:
        print "Output was not checked for correctness"

    return ErrorType.Success

def debug_benchmark(bmk, version_name, input_name, check=True, extra_opts=[], platform=None):
    """Debug the benchmark."""
    try: impl = bmk.impls[version_name]
    except KeyError:
        print "Cannot find benchmark version"
        return ErrorType.CannotFindVersion

    try: data = bmk.datas[input_name]
    except KeyError:
        print "Cannot find data set"
        return ErrorType.CannotFindDataSet

    # Run the benchmark
    return impl.debug(bmk, data, check, extra_opts=extra_opts, platform=platform)


text:
using System;
using System.Collections;
using System.IO;
using Rikrop.Core.Network.WebClient;
using NUnit.Framework;

namespace Rikrop.Core.Network.Tests
{
    [TestFixture]
    public class CharsetAnalizerTest
    {
        private const string HtmlPageWithCharset1 =
            "<!DOCTYPE html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";

        private const string HtmlPageWithCharset2 =
            "<!DOCTYPE html><meta name=\"author\" value=\"me\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";

        private const string HtmlPageWithCharset3 =
            "<!DOCTYPE html><meta charset=\"utf-8\" />";

        private const string HtmlPageWithoutCharset1 = "<!DOCTYPE html>";

        private const string HtmlPageWithoutCharset2 =
            "<!DOCTYPE html><meta name=\"author\" value=\"me\">";

        public static IEnumerable TestCases
        {
            get
            {
                yield return new TestCaseData(HtmlPageWithCharset1, "utf-8");
                yield return new TestCaseData(HtmlPageWithCharset2, "utf-8");
                yield return new TestCaseData(HtmlPageWithCharset3, "utf-8");
                yield return new TestCaseData(HtmlPageWithoutCharset1, null);
                yield return new TestCaseData(HtmlPageWithoutCharset2, null);

                var russ = File.ReadAllText("TestData/russ.ru.txt");
                yield return new TestCaseData(russ, "utf-8");
            }
        }

        [Test]
        [TestCase("TestData/utf-8.txt", "utf-8")]
        [TestCase("TestData/win1252.txt", "windows-1252")]
        [TestCase("TestData/win1252-2.txt", "windows-1252")]
        [TestCase("TestData/win1251.txt", "windows-1251")]
        public void ShouldAutodetectCharset(string filePath, string expectedCharset)
        {
            var stream = File.OpenRead(filePath);
            var analizer = new CharsetAnalizer();
            var charset = analizer.AutoDetectCharset(stream);

            Assert.AreEqual(0, string.Compare(expectedCharset, charset, StringComparison.OrdinalIgnoreCase));
        }

//        [Test]
//        [TestCase("http://www.w3.org/", "utf-8")]
        public void ShouldGetCharsetFromResponse(string url, string expectedCharset)
        {
            var analizer = new CharsetAnalizer();
            var charset = analizer.GetCharsetForUrl(url);

            Assert.AreEqual(0, string.Compare(expectedCharset, charset, StringComparison.OrdinalIgnoreCase));
        }

        [Test]
        [TestCaseSource("TestCases")]
        public void ShouldParseMetaTag(string input, string expectedCharset)
        {
            var analizer = new CharsetAnalizer();
            var charset = analizer.GetCharsetFromMetadata(input);

            Assert.AreEqual(0, string.Compare(expectedCharset, charset, StringComparison.OrdinalIgnoreCase));
        }
    }
}